package example.demo.config;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import example.demo.mybatisplugin.RoutePlugin;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

//@Order(500)
@Configuration
@MapperScan("example.demo.mapper")
public class MybatisplusConfig {
    @Autowired
    RoutePlugin routePlugin;

    /**
     * <? 多数源下在yaml文件关于mybatis-plus的配置是无效的。
     */
    @Bean
    //会让MybatisPlusAutoConfiguration配置的SqlSessionFactory失效
    public SqlSessionFactory sqlSessionFactory(ApplicationContext applicationContext, @Qualifier("dynamicDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
//        bean.setDataSource(dynamicDataSource(xiaoxiaosecondkillDS(), xiaoxiaoDS()));
        bean.setDataSource(dataSource);
        Interceptor[] interceptors = new Interceptor[]{routePlugin};
        bean.setPlugins(interceptors);
        //mapper.xml文件
        bean.setMapperLocations(applicationContext.getResources("classpath:mapper/*Mapper.xml"));
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        //日志打印
        configuration.setLogImpl(StdOutImpl.class);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }


}
